package com.xcity.robot.net.test;

import java.io.File;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcity.game.account.Platform;
import com.xcity.game.buildv2.BuildV2.State;
import com.xcity.game.buildv2.BuildV2Part;
import com.xcity.pomelo.request.AdventurePlayRequest;
import com.xcity.pomelo.request.BuildCreateV2Request;
import com.xcity.pomelo.request.BuildPartLevelUpV2Request;
import com.xcity.pomelo.request.LoginRequest;
import com.xcity.pomelo.request.PlayerLoadRequest;
import com.xcity.pomelo.response.AdventurePlayResponse;
import com.xcity.pomelo.response.BuildCreateV2Response;
import com.xcity.pomelo.response.BuildV2PartLevelUpResponse;
import com.xcity.pomelo.response.LoginResponse;
import com.xcity.pomelo.response.PlayerLoadResponse;
import com.xcity.pomelo.response.PlayerLoadResponse.PlayerDetail;
import com.xcity.pomelo.response.Response;
import com.xcity.robot.net.Session;
import com.xcity.robot.net.packet.BinaryPacket;
import com.xcity.robot.net.packet.PacketHandler;
import com.xcity.robot.net.util.SessionUtils;
import com.xcity.robot.net.util.Settings.NameBuilder;
import com.xcity.robot.net.websocket.HandshakeListener;

import naga.x.net.Packet;
import naga.x.util.CommonUtils;
import naga.x.util.IOUtils;

public class Resources {

	public static class PomeloHandshakeListener implements HandshakeListener {
		@Override
		public void handshakeOk(Session session) {
			LoginRequest req = new LoginRequest();
//		private String userName;
			req.setUserId(CommonUtils.randomText(8));
//		private String userId; // @see User#channelUid
//		req.setUserName("__x" + CommonUtils.randomText(3));
			req.setUserName(NameBuilder.nextName());
//		private String ip;
			req.setIp("localhost");
//		private String channel;
			req.setChannel("1");
			req.setPlatform(Platform.ANDROID.ordinal());
			req.setSerial(SessionUtils.nextSerial(session));
			session.write(req, loginResponseHandler);
		}
	}
	
	public static PacketHandler loginResponseHandler = new PacketHandler() {
		@Override
		public void handle(Session session, Packet packet) {
			byte[] b = ((BinaryPacket) packet).toBinary();
			LoginResponse res = JSON.parseObject(b, LoginResponse.class);
			if (res != null && BatchCreateRobotsMain.hasNameAndIcon()) {
				PlayerLoadRequest req = new PlayerLoadRequest();
				req.setUid(res.user.userId);
				req.setName(BatchCreateRobotsMain.nextName());
				req.setCity("朝阳");
				req.setProvince("北京");
				req.setHeadimgurl(BatchCreateRobotsMain.nextIcon());
				req.setSex((byte) (CommonUtils.randomBoolean() ? 1 : 2));
				req.setSerial(SessionUtils.nextSerial(session));
				
				session.write(req, playerLoadResponseHandler);
				IOUtils.write(new File("C:/Users/yang.li/Desktop/server_release/robot_names/accounts.txt"), res.user.userId + System.lineSeparator(), IOUtils.UTF8, true);
				System.out.println("账号创建成功..." + res.user.userName + "(" + res.user.userId + ")");
			}
		}
	};
	
	public static PacketHandler playerLoadResponseHandler = new PacketHandler() {
		@Override
		public void handle(Session session, Packet packet) {
			byte[] b = ((BinaryPacket) packet).toBinary();
			PlayerLoadResponse res = JSON.parseObject(b, PlayerLoadResponse.class);
			session.setAttribute(KEY_PLAYER, res.roler);
			// 请求建造第一个建筑
			requestCreateBuilding(session, 10000);
			// 请求转奇遇
			session.setAttribute(KEY_ADV_N, 1);
			AdventurePlayRequest req = new AdventurePlayRequest();
			req.setSerial(SessionUtils.nextSerial(session));
			session.write(req, adventurePlayResponseHandler);
			System.out.println("角色创建成功..." + res.roler.roleName + "(" + res.roler.roleId + ")");
		}
	};
	
	static void requestCreateBuilding(Session session, int buildId) {
		requestCreateBuilding(session, buildId, null);
	}
	
	static void requestCreateBuilding(Session session, int buildId, PacketHandler handler) {
		BuildCreateV2Request req = new BuildCreateV2Request();
		req.setSerial(SessionUtils.nextSerial(session));
		req.setId(buildId);
		session.write(req, handler);
		session.setAttribute(KEY_BUILDING_ID, buildId);
	}
	
	static final String KEY_BUILDING_ID = "build";
	static final String KEY_BUILDING_PART = "buildPart";
	static final String KEY_ADV_N = "advN";
	static final String KEY_ITEMS = "items"; // 建材箱
	static final String KEY_PLAYER = "player";
	
	static PlayerDetail getPlayer(Session session) {
		return session.getAttribute(KEY_PLAYER);
	}
	
	static int getAttributeInt(Session session, String key) {
		Integer n = session.getAttribute(key);
		return n != null ? n : 0;
	}
	
	public static PacketHandler adventurePlayResponseHandler = new PacketHandler() {
		@Override
		public void handle(Session session, Packet packet) {
			byte[] b = ((BinaryPacket) packet).toBinary();
			AdventurePlayResponse res = JSON.parseObject(b, AdventurePlayResponse.class);
			if (res.pos == 0) { // 建材箱
				Integer n = session.getAttribute(KEY_ITEMS);
				if (n == null) {
					n = 0;
				}
				session.setAttribute(KEY_ITEMS, n + 1);
			}
			Integer n = session.getAttribute(KEY_ADV_N);
			if (n == null) {
				n = 0;
			}
			if (n < 50) { // 最多转50次奇遇
				session.setAttribute(KEY_ADV_N, n + 1);
				AdventurePlayRequest req = new AdventurePlayRequest();
				req.setSerial(SessionUtils.nextSerial(session));
				session.write(req, adventurePlayResponseHandler);
			} else {
				// 使用建材箱auto...升级建筑
				requestBuildLvlUp(session);
			}
			PlayerDetail player = getPlayer(session);
			System.out.println("奇遇..." + player.roleName + "(" + player.roleId + ")");
		}
	};
	
	public static PacketHandler buildCreateResponseHandler = new PacketHandler() {
		@Override
		public void handle(Session session, Packet packet) {
			byte[] b = ((BinaryPacket) packet).toBinary();
			JSONObject json = (JSONObject) JSON.parse(b);
			if (json.getIntValue("code") == Response.CODE_OK) {
				BuildCreateV2Response res = JSON.parseObject(b, BuildCreateV2Response.class);
				session.setAttribute(KEY_BUILDING_ID, res.getId());
				session.setAttribute(KEY_BUILDING_PART, 0);
				requestBuildLvlUp(session);
				PlayerDetail player = getPlayer(session);
				System.out.println("建造..." + player.roleName + "(" + player.roleId + ")" + res.getId());
			} else {
				System.out.println(json);
			}
		}
	};
	
	static void requestBuildLvlUp(Session session) {
		int buildId = session.getAttribute(KEY_BUILDING_ID);
		Integer buildPart = session.getAttribute(KEY_BUILDING_PART);
		if (buildPart == null) {
			session.setAttribute(KEY_BUILDING_PART, buildPart = 0);
		}
		BuildPartLevelUpV2Request req = new BuildPartLevelUpV2Request();
		req.setId(buildId);
		req.setPart(buildPart);
		session.write(req, buildLvlUpResponseHandler);
	}
	
	public static PacketHandler buildLvlUpResponseHandler = new PacketHandler() {
		@Override
		public void handle(Session session, Packet packet) {
			byte[] b = ((BinaryPacket) packet).toBinary();
			JSONObject json = (JSONObject) JSON.parse(b);
			if (json.getIntValue("code") == Response.CODE_OK) {
				BuildV2PartLevelUpResponse res = JSON.parseObject(b, BuildV2PartLevelUpResponse.class);
				if (res.state == State.BUILT) {
					// 建造下一个建筑
					if (res.id == 10000) {
						int buildId = res.id + 1;
						requestCreateBuilding(session, buildId, buildCreateResponseHandler);
					}
				} else {
					int buildPart = res.part.index;
					if (res.part.level >= BuildV2Part.MAX_LEVEL) { // 部位满级
						++buildPart;
					}
					session.setAttribute(KEY_BUILDING_PART, buildPart);
					requestBuildLvlUp(session);
				}
				PlayerDetail player = getPlayer(session);
				System.out.println("建筑升级..." + player.roleName + "(" + player.roleId + ")" + res.id);
			} else {
				System.out.println(json);
				int buildPart = getAttributeInt(session, KEY_BUILDING_PART);
				if (buildPart < 4) {
					session.setAttribute(KEY_BUILDING_PART, ++buildPart);
					int buildId = getAttributeInt(session, KEY_BUILDING_ID);
					requestBuildLvlUp(session);
				}
			}
		}
	};
	

}
